import iconv from 'iconv-lite'
import {Buffer} from 'buffer'


/**
 * 将文本编码为 GB18030 字节数组
 * @param text UTF-8 文本
 * @returns Uint8Array
 */
export function encodeToGB18030(text: string): Uint8Array {
    const buffer = iconv.encode(text, 'gb18030')
    return new Uint8Array(buffer)
}

/**
 * 将 GB18030 字节数组解码为 UTF-8 文本
 * @param bytes GB18030 字节数组
 * @returns UTF-8 文本
 */
export function decodeFromGB18030(bytes: Uint8Array): string {
    return iconv.decode(Buffer.from(bytes), 'gb18030')
}

export function decodeFromUTF8(bytes: Uint8Array): string {
    return iconv.decode(Buffer.from(bytes), 'utf8')
}

export function canEncodeWithGB18030(char: string) {
    try {
        const buffer = iconv.encode(char, 'gb18030');
        // 如果编码后长度大于2个字节且第一个字节是0x3F(?)，
        // 可能表示无法正确编码
        // console.log('buffer', buffer)
        // return !(buffer.length > 2 && buffer[0] === 0x3F);
        return buffer.length <= 2;
    } catch (e) {
        return false;
    }
}